// pages/answer/index.js
/**power by TarryLi */
var app = getApp();
var that = this;
var result = 0;
var problemNums = 1;
var timeInterval;
var stop = 0;
var j = 10;
var points_1 = 0;
var points_2 = 0;
var flag = false;
var openid = null;
var getFlag = false;


Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatarUrl: "",//用户头像  
      nickName: "",//用户昵称  
    },
    answer:"",
    confrim:"",
    waiting:"",
    msg:"",
    problemNum: "",
    timeCount: "",
    OpponentAvatarUrl: "",
    Opponentnickname: "",
    problem: "",
    choice_0: "",
    choice_1: "",
    choice_2: "",
    choice_3: "",
    point_1: "",
    point_2: "",
    heigher_1: "",
    heigher_2: "",
    c1: "",
    c2: "",
    c3: "",
    c4: "",
  },

  close: function(){
    wx.closeSocket({
      code: 0,
      reason: '',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

//显示匹配页面
    that.setData({
      userInfo: getApp().globalData.userInfo,
      msg: '正在为你匹配对手...',
      waiting: 'block',
      confrim: 'none',
      answer: 'none',
      point_1: 0,
      point_2: 0,
    })

//连接socket
    wx.connectSocket({
      url: getApp().globalData.ws +'/echo.do',
      header: { 'content-type': 'application/json'},
      method: 'GET',
      protocols: [],
      success: function (res) {
        console.log('websocket connect success!');
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
       },
    })

  var obj = new Object;
    obj.nickname = getApp().globalData.userInfo.nickName;
    obj.avatarUrl = getApp().globalData.userInfo.avatarUrl;
    obj.openid = getApp().globalData.openid;
//检测socket连接是否打开
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开了！');
      console.log(obj);
      wx.sendSocketMessage({
        data: JSON.stringify(obj)
      })
    })

    wx.onSocketError(function (res) {
      res = JSON.stringify(res);
      console.log('WebSocket错误！' + res);
    })
//接受socket数据
    wx.onSocketMessage(function(res){
      console.log('第一次：' + res.data);
      res = JSON.parse(res.data);
      if(res.state == 1){
        getApp().globalData.roomnum = res.roomnumber;
        res = JSON.parse(res.user);
        console.log(res);
        getApp().globalData.Opponentnickname = res.nickname;
        getApp().globalData.OpponentAvatarUrl = res.avatarUrl;
        openid = res.openid;
        getFlag = true;
        setTimeout(function () {
          that.goConfrim(res.avatarUrl, res.nickname);
        }, 1000);
      }
      if(res.state == 2){
        that.setData({
          problem: res.title.title,
          choice_0: res.title.answer[0],
          choice_1: res.title.answer[1],
          choice_2: res.title.answer[2],
          choice_3: res.title.answer[3],
          problemNum: problemNums,
        })
        stop = res.stop;
        result = res.title.answer[4];
        that.setTime();
        problemNums = problemNums + 1;
        flag = true;
        that.setData({
          c1: '',
          c2: '',
          c3: '',
          c4: '',
        })
      }
      //设置别人的分数
      if(res.state == 3){
        console.log("获取对方分数" + res);
        points_2 = points_2 + res.points;
        var height_2 = (1 - (points_2 / 500)) * 100;
        that.setData({
          point_2: points_2,
          heigher_2: height_2,
        })
      }
      if(res.state == 4){
        getApp().globalData.myscore = points_1;
        getApp().globalData.opscore = points_2;
        setTimeout(function () {
          wx.closeSocket();
          that.reset();
          wx.redirectTo({
            url: '../result/index',
          });
        }, 1500)
      }
      if (res.state == 5) {
        console.log('连接错误返回！')
        wx.closeSocket();
        wx.redirectTo({
          url: '../index/index',
        })
      }
    })
    
  },
//reset
reset: function(){
  result = 0;
  problemNums = 1;
  timeInterval;
  stop = 0;
  j = 10;
  points_1 = 0;
  points_2 = 0;
  flag = false;
  openid = null;
  clearInterval(timeInterval);
  getFlag = false;
},

//倒计时
  setTime: function () {
    var timeCount = 'timeCount';
    var that = this;
    j = 10;
    timeInterval = setInterval(function () {
      that.setData({
        [timeCount]: j,
      });
      j--;
      if (j < 0) {
        clearInterval(timeInterval);
        that.answerOver(0);
      }
    }, 1000)
  },

//点击判分
  answers: function (event) {
    var that = this;
    if (flag) {
      flag = false;
      var points;
      var answers = event.currentTarget.id;
      var resultes = 0;
      answers = parseInt(answers);
      result = parseInt(result);
      if (answers == result) {
        switch (j) {
          case 10:
            points = 100;
            break;
          case 9:
            points = 90;
            break;
          case 8:
            points = 80;
            break;
          case 7:
            points = 70;
            break;
          case 6:
            points = 60;
            break;
          case 5:
            points = 50;
            break;
          case 4:
            points = 40;
            break;
          case 3:
            points = 30;
            break;
          case 2:
            points = 20;
            break;
          case 1:
            points = 10;
            break;
          case 0:
            points = 10;
            break;
        }
        console.log('answes ！！！');
        that.setMyanswer(points, answers, 1);
        that.answerOver(points);
        clearInterval(timeInterval);
      } else {
        that.answerOver(0);
        that.setMyanswer(0, answers, 0);
        console.log('success-1');
        clearInterval(timeInterval);
      }
    }
  },


//设置自己的答案和分数
  setMyanswer: function (point, resultss, TF) {
    var that = this;
    var tf;
    points_1 = points_1 + point;
    var height_1 = (1 - (points_1 / 500)) * 100;
    if (TF == 1) {
      tf = '#8cf9a3';
      console.log('setMy!!!');
    } else {
      if (TF == 0) {
        tf = '#f898b3';
        console.log('setMy!!!');
      }
    }
    switch (resultss) {
      case 1:
        that.setData({
          c1: tf,
        })
        break;
      case 2:
        that.setData({
          c2: tf,
        })
        break;
      case 3:
        that.setData({
          c3: tf,
        })
        break;
      case 4:
        that.setData({
          c4: tf,
        })
        break;
    }
    that.setData({
      point_1: points_1,
      heigher_1: height_1,
    })
  },

//回答问题后
  answerOver: function (point) {
    if(getFlag){
      wx.request({
        url: getApp().globalData.url +'/send.do',
      method: "GET",
      data: { room: getApp().globalData.roomnum,points: point,openid: openid,stop: stop},
      header: {
        'content-type': 'json'
      },
      success: function (res) {
        console.log('yes');
      }
    })
    }
  },

//跳转匹配成功页面
  goConfrim: function(imgurl,nickname){
    var that = this;
    this.setData({
      waiting: 'none',
      confrim: 'block',
      answer: 'none',
      Opponentnickname: nickname,
      OpponentAvatarUrl: imgurl,
    })
    setTimeout(function () {
      that.setData({
        waiting: 'none',
        confrim: 'none',
        answer: 'block',
      })
      //get请求题目
      wx.request({
        url: getApp().globalData.url +'/send.do',
        method: "GET",
        data: {room:getApp().globalData.roomnum,openid:openid,stop:stop},
        header: {
          'content-type': 'json'
        },
        success: function (res) {
          console.log('yes');
        }
      })
    }, 1500)
  },

  onHide: function () {
    wx.closeSocket();
    this.reset();
    console.log('断开1')
  }, 

  onUnload: function () {
    wx.closeSocket();
    this.reset();
    console.log('断开2');
  }, 
})